import { preview } from 'vite'

import baseConfig from './config/vite.base.config.ts'
import previewConfig from './config/vite.preview.config.ts'
import myConfig from '../vite.my.config.ts'

import { mergeObject } from '../src/utils//mergeOptions.ts'

let _previewConfig = previewConfig
function isEmptyValue(value: any): boolean {
  if (value === null || value === undefined) return true
  if (typeof value === 'string' && value.trim() === '') return true
  if (Array.isArray(value) && value.length === 0) return true
  if (typeof value === 'object' && Object.keys(value).length === 0) return true
  return false // false、0 都算有值
}
if (Object.hasOwnProperty.call(myConfig, 'preview')) {
  // @ts-ignore
  _previewConfig = mergeObject(myConfig.preview, previewConfig)
}
// 这个配置存在key都可以用service中内的配置替代
if (Object.hasOwnProperty.call(myConfig, 'server')) {
  const keys = Object.keys(previewConfig)
  for (let i = 0; i < keys.length; ++i) {
    const key = keys[i]
    // @ts-ignore
    if (isEmptyValue(_previewConfig[key]) && Object.hasOwnProperty.call(myConfig, key)) {
      // @ts-ignore
      _previewConfig[key] = myConfig.server[key]
    }
  }
}

const config = Object.assign(mergeObject(baseConfig, myConfig), {
  preview: _previewConfig,
})
const previewServer = await preview({
  configFile: false,
  ...config,
})
previewServer.printUrls()
